require 'match'

default_platform(:ios)
setup_travis

platform :ios do

  desc "Run UI and Unit tests"
  lane :tests do

    # Parallel UI testing disabled because Travis can't handle it
    # -parallel-testing-enabled NO cause problems with connections to simulators while testing
    # Old flag -disable-concurrent-testing used instead

    sh("xcrun simctl shutdown all")
    sh("xcrun simctl erase all")

    destinations = [
      "-destination platform=iOS\\ Simulator,name=iPhone\\ 14\\ Pro\\ Max",
      "-destination platform=iOS\\ Simulator,OS=15,name=iPhone\\ 14",
      "-destination platform=iOS\\ Simulator,OS=15,name=iPhone\\ 14 Pro",
      "-destination platform=iOS\\ Simulator,OS=15,name=iPhone\\ 14 mini",
    ]

   destinations.each do |destination|
      sh("set -o pipefail && xcodebuild -scheme \"Demo\" #{destination} clean test | xcpretty --color")
      sh("xcrun simctl shutdown all")
   end

  end

  desc "Push a new beta build to TestFlight"
  lane :beta do

    bundle_id = "com.mapbox.MapboxSearchDemoApplication"
    xcodeproj_path = "MapboxSearch.xcodeproj"

    sync_code_signing(type: "development")
    disable_automatic_code_signing(
      path: xcodeproj_path,
      team_id: "GJZR2MEM28",
      profile_name: lane_context[SharedValues::MATCH_PROVISIONING_PROFILE_MAPPING][bundle_id],
      targets: ["Demo"]
    )

    build_number = `TZ=UTC date +%Y%m%d%H%M`[0..-2] + ENV["CIRCLE_BUILD_NUM"]
    increment_build_number_in_plist(
      build_number: build_number,
      xcodeproj: xcodeproj_path,
      target: 'Demo'
    )
    sync_code_signing
    build_app(scheme: "Demo",
              export_method: "app-store",
              export_options: {
                provisioningProfiles: {
                  bundle_id => lane_context[SharedValues::MATCH_PROVISIONING_PROFILE_MAPPING][bundle_id]
                }
              })

    ipa_path = lane_context[SharedValues::IPA_OUTPUT_PATH]
    sh("xcrun altool --upload-app -f \"#{ipa_path}\" -t ios -u #{ENV["MATCH_USERNAME"]} -p @env:ALTOOL_PASSWORD")
    UI.message("Build ##{build_number}")
  end
end
